<?php
namespace App\Repositories;

use App\Models\Quiz;
use App\Models\Statement;
use App\Models\Bet;
use Illuminate\Support\Facades\DB;

class StatementRepository
{
    /**
     * @param $groupUserId
     * @param $copper
     * @param string $explanation
     */
    public static function log($groupUserId, $copper, $modelId, $type = 'default', $explanation = '')
    {
        $statement = new Statement;
        $statement->copper = $copper;
        $statement->group_user_id = $groupUserId;
        $statement->explanation = $explanation;
        $statement->model_id = $modelId;
        $statement->model_type = $type;
        $statement->save();
    }


    /**
     * 记录下注
     *
     * @param Bet $bet
     * @param string $slug
     * @param bool $debit
     */
    public static function recordBet(Bet $bet, $slug, $debit = true, $copperKeyName = 'copper')
    {
        self::log(
            $bet->group_user_id,
            ($debit ? 1 : -1) * $bet->{$copperKeyName},
            $bet->id, "bet.{$slug}", json_encode([
                'id' => $bet->id,
                'copper' => $bet->copper,
                'odds' => $bet->odds,
                'quiz_item_id' => $bet->quiz_item_id,
                'status' => $bet->status,
            ])
        );
    }

    /**
     * 记录开奖
     *
     * @param Quiz $quiz
     * @param int $copper
     */
    public static function recordAnnounce(Quiz $quiz, int $copper)
    {
        $explanation = Bet::where('quiz_id', $quiz->id)
            ->where('status', QuizRepository::BET_STATUS_FINISHED)
            ->groupBy('result')
            ->get(['result', DB::raw('count(*) cnt')])
            ->pluck('cnt', 'result');

        self::log(
            $quiz->createrAccountInThisGroup->id,
            $copper,
            $quiz->id, 'quiz', $explanation
        );
    }
}